import mqtt from "mqtt"

const options = {
  clean: true,
  connectTimeout: 4000,
  clientId: "xndp" + Math.random().toString(16).substr(2, 8),
  username: "xndp",
  password: "123456"
}

const brokerUrl = "ws://121.5.46.95:8083/mqtt" // 使用公共测试服务器

class MQTTClient {
  constructor() {
    this.client = null
  }

  connect() {
    this.client = mqtt.connect(brokerUrl, options)

    this.client.on("connect", () => {
      console.log("连接成功")
      this.subscribe("xining/screen")
      this.subscribe("topic/push/appeal/detail")
    })

    this.client.on("error", (error) => {
      console.error("连接失败", error)
    })
  }

  subscribe(topic) {
    this.client.subscribe(topic, { qos: 0 }, (err) => {
      if (!err) {
        console.log(`订阅成功: ${topic}`)
      }
    })
  }

  onMessage(callback) {
    this.client.on("message", (topic, message) => {
      callback(topic, message.toString())
    })
  }

  publish(topic, message) {
    this.client.publish(topic, message, { qos: 0 })
  }

  disconnect() {
    console.log("断开连接") // 打印断开连接的日志，方便调试和确认连接是否正常关闭
    this.client?.end()
  }
}

export const mqttClient = new MQTTClient()
